package com.common.app.utls.network.interceptor

import com.common.app.data.bean.BaseResponse
import com.common.app.data.bean.KeyEvents
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.coroutines.runBlocking
import okhttp3.*
import okio.Buffer
import okio.GzipSource
import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：21/11/2023
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class TokenInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val response: Response = chain.proceed(request)
//        val code = response.header("token_code")

        response.body?.let { responseBody ->
            if (response.code == 200) {

                val source = responseBody.source()
                source.request(Long.MAX_VALUE)
                var buffer = source.buffer

                if ("gzip".equals(response.headers["Content-Encoding"], ignoreCase = true)) {
                    GzipSource(buffer.clone()).use { gzippedResponseBody ->
                        buffer = Buffer()
                        buffer.writeAll(gzippedResponseBody)
                    }
                }

                val contentType = responseBody.contentType()
                val charset: Charset =
                    contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
                try {
                    val tempRes = Gson().fromJson(buffer.clone().readString(charset), BaseResponse::class.java)
                    if (tempRes.code == 1) {  // token失效过期
                        LiveEventBus.get(KeyEvents.EVENT_TOKEN_EXPIRED, String::class.java).post("!")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return response
    }
}
